package com.slkj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.*;
import com.slkj.entity.Area;
import com.slkj.entity.UserRole;
import com.slkj.entity.Userinfo;
import com.slkj.service.UserService;
import com.slkj.util.InputCheck;
import com.slkj.util.RequestResponseBox;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.xml.soap.Node;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author admin
 * @version 1.0.0
 * @ClassName UserController.java
 * @Description TODO
 * @createTime 2020年03月06日 17:08:00
 */
@CrossOrigin
@Transactional
@RestController
@RequestMapping("${address.prefix}/user")
public class UserController {

    private Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public Result login(@RequestBody String data) {

        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject == null) {
            throw new NullPointerException("空指针异常");
        }
        log.info("---------------------------------------------->>>>>>>>进入/GC/login方法");
        String username = jsonObject.getString("username");
        log.info("---------------------------------------------->>>>>>>>获取用户的登录名" + username);
        String password = jsonObject.getString("password");

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            log.error("登陆时参数为空");
            return new Result(false, StatusCode.ERROR, "用户名或者密码不能为空!");
        }


        Subject subject = SecurityUtils.getSubject();
        Userinfo userinfo = userService.findUserinfoByUsername(username);
        if (userinfo == null) {
            log.error("---------------------------------------------->>>>>>>>用户不存在");
            return new Result(true, StatusCode.OK, "用户不存在!");
        }
        if (!subject.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                log.error("---------------------------------------------->>>>>>>>用户名或者密码错误");
                return new Result(false, StatusCode.LOGINERROR, "用户名或密码错误!");
            }
            userinfo.setPrevLoginTime(new Date());


            userService.insertPrevLoginTime(userinfo);
            userService.updateIsOnlineByUsername(userinfo);
            subject.getSession().setAttribute("username", username);

            log.info("---------------------------------------------->>>>>>>登录成功");
            return new Result<String>(true, StatusCode.OK, "登录成功", subject.getSession().getId());
        }


        return new Result<String>(true, StatusCode.COMPELETELOGIN, "用户已经登录", username);

    }


    @PostMapping("/register")
    public Result register(@RequestBody String data) {
        log.info("--------------------------------->>>进入 Result register(@RequestBody String data) 方法");
        JSONObject jsonObject = JSONObject.parseObject(data);
        String usernameToken = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(usernameToken) || usernameToken.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }


        String roleId = jsonObject.getString("roleId");
        String username = jsonObject.getString("username");
        String phone = jsonObject.getString("phone");
        String email = jsonObject.getString("email");
        String aId = jsonObject.getString("aId");
        log.info("---------------------------------->>>获取注册时的角色Id" + roleId);
        log.info("---------------------------------->>>获取注册时的用户姓名" + username);
        log.info("---------------------------------->>>获取用户的手机号码" + phone);


        if (StringUtils.isBlank(username) || StringUtils.isBlank(phone) || StringUtils.isBlank(roleId) || StringUtils.isBlank(email)
                || StringUtils.isBlank(aId)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        if (!StringUtils.isNumeric(roleId) || !StringUtils.isNumeric(aId)) {
            return new Result(false, StatusCode.ERROR, "参数格式有误");
        }


        if (!InputCheck.isMobile(phone)) {
            return new Result(true, StatusCode.OK, "手机号码格式不正确,请重新检查输入");
        }

        if (!InputCheck.isEmail(email)) {
            return new Result(true, StatusCode.OK, "邮箱格式不正确,请重新检查输入");
        }


        //防止重复注册
        Userinfo userinfo = userService.findUserinfoByUsername(username);

        if (userinfo != null) {
            log.info("用户名已经存在");
            return new Result(true, StatusCode.Repetition, "用户名已经存在");
        }


        userService.register(aId, username, phone, roleId, email);


        log.info("---------------------------------------------->>>>>>>注册成功");
        return new Result<String>(true, StatusCode.OK, "success");
    }


    /**
     * @hrows
     * @titlea 添加角色(类型, 所属, 部分, 职务)
     * @description
     * @author liman
     */
    @PostMapping("/insertRole")
    public Result insertRole(@RequestBody String data) {
        log.info("进入 insertUserRole(@RequestBody  String data) 方法");
        JSONObject jsonObject = JSON.parseObject(data);
        if (jsonObject == null) {
            throw new NullPointerException("空指针异常");
        }
        String usernameToken = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(usernameToken) || usernameToken.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        String roleName = jsonObject.getString("roleName");
        String pId = jsonObject.getString("pId");
        String tId = jsonObject.getString("tId");


        log.info("----------------------->>>获取参数roleName=" + roleName);
        log.info("----------------------->>>获取参数pId=" + pId);
        log.info("----------------------->>>获取参数tId=" + tId);

        if (StringUtils.isBlank(roleName) || StringUtils.isBlank(pId) || StringUtils.isBlank(tId)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        UserRole userRole = new UserRole();
        userRole.setpId(pId);
        userRole.setRoleName(roleName);
        userRole.settId(tId);


        //添加用户角色
        log.info("获取角色信息" + userService.toString());
        userService.insertUserRole(userRole);


        log.info("添加角色成功" + userRole.toString());
        return new Result(true, StatusCode.OK, "success");
    }

    /**
     * @hrows
     * @titlea 查询类型
     * @description
     * @author liman
     */
    @PostMapping("/getRole")
    public Result getRole1(@RequestBody String data) {
        log.info("----------------------->>>进入getRole()");
        JSONObject jsonObject = JSON.parseObject(data);
        String pIdString = jsonObject.getString("pId");
        log.info("----------------------->>>获取参数pid=" + pIdString);
        String usernameToken = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(usernameToken) || usernameToken.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        int pId = 0;
        if (pIdString == null || pIdString.equals("")) {
            pId = 0;
        } else {
            try {
                pId = Integer.parseInt(pIdString);
            } catch (NumberFormatException e) {
                pId = 0;
            }
        }

        log.info("----------------------->>>pid参数结果=" + pId);

        //添加用户角色
        List<UserRole> userRoleList = userService.getRoleList(pId);
        if (userRoleList == null || userRoleList.size() <= 0) {
            log.error("查询角色,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }

        log.info("查询角色组合成功,返回View");
        return new Result(true, StatusCode.OK, "查询角色组合成功", userRoleList);
    }


    @PostMapping("/getUser")
    public Result getUser() {
        log.info("----------------------->>>进入getUser()");

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        log.info("----------------------->>>获取用户名=" + username);

        //查询用户
        Userinfo userinfo = userService.getUser(username);
        if (userinfo == null) {
            log.error("查询角色,无数据");
            throw new NullPointerException("空指针异常");
        }

        log.info("查询用户成功,返回View");
        return new Result(true, StatusCode.OK, "查询用户成功", userinfo);
    }


    /**
     * @hrows
     * @titlea 分页查询用户
     * @description
     * @author liman
     */
    @PostMapping("/getUserinfoAll")
    public Result getUserinfoAll(@RequestBody String data) throws IOException {
//        String data = RequestJson.getRequestJsonString(request);
        log.info("----------------------->>>getUserinfoAll(@RequestBody(required = false) String data, @Value(\"${pageSize}\") String pageSizeString)");
        JSONObject jsonObject = JSON.parseObject(data);
        String search = jsonObject.getString("search");
        String gotoPageString = jsonObject.getString("page");
        String pageSizeString = jsonObject.getString("pageSize");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        if (StringUtils.isNotBlank(search)) {
            search = search.trim();
        }

        log.info("----------------------->>>获取参数搜素条件=" + search);
        log.info("----------------------->>>获取参数第几页=" + gotoPageString);
        log.info("----------------------->>>获取参数一页几条=" + pageSizeString);

        int gotoPage = 1;

        if (StringUtils.isNotBlank(gotoPageString) && StringUtils.isNumeric(gotoPageString)) {
            gotoPage = Integer.parseInt(gotoPageString);
        }

        int pageSize = 10;
        if (StringUtils.isNotBlank(pageSizeString) && StringUtils.isNumeric(pageSizeString)) {
            pageSize = Integer.parseInt(pageSizeString);
        }


        PageInfo<UserinfoDTO> userinfoDTOList = userService.getUserinfoAll(search, gotoPage, pageSize);


        if (userinfoDTOList == null || userinfoDTOList.getSize() <= 0) {
            log.error("分页查询用户数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }

        log.info("查询用户成功,返回View");
        return new Result(true, StatusCode.OK, "分页查询用户数据成功", userinfoDTOList);
    }

    /**
     * @hrows
     * @titlea 根据userId查看用户
     * @description
     * @author liman
     */
    @PostMapping("/getUserinfo")
    public Result getUserinfo(@RequestBody String data) throws IOException {
        log.info("----------------------->>>gegetUserinfo(@RequestBody String data) throws IOException");
        JSONObject jsonObject = JSON.parseObject(data);
        if (jsonObject == null) {
            throw new NullPointerException("空指针异常");
        }
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        String userId = jsonObject.getString("userId");
        if (StringUtils.isBlank(userId)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }
        if (!StringUtils.isNumeric(userId)) {
            return new Result(false, StatusCode.ERROR, "参数格式有误");
        }
        UserinfoDTO userinfoDTO = userService.getUserinfo(userId);

        if (userinfoDTO == null) {
            log.error("查询用户数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }

        log.info("查询用户成功,返回View");
        return new Result(true, StatusCode.OK, "查询用户数据成功", userinfoDTO);

    }


//    /**
//     * @hrows
//     * @titlea 根据userId查看用户
//     * @description
//     * @author liman
//     */
//    @RequestMapping("/updateUserinfo")
//    public Result updateUserinfo(@RequestBody String data) throws IOException {
//        log.info("----------------------->>>updateUserinfo(@RequestBody String data)");
//        JSONObject jsonObject = JSON.parseObject(data);
//        if (jsonObject == null) {
//            throw new NullPointerException("空指针异常");
//        }
//
//        String userId = jsonObject.getString("userId");
//        if (StringUtils.isBlank(userId)) {
//            return new Result(false, StatusCode.ERROR, "参数为空");
//        }
//        if (!StringUtils.isNumeric(userId)) {
//            return new Result(false, StatusCode.ERROR, "参数格式有误");
//        }
//
//        UserinfoDTO userinfoDTO = userService.updateUserinfo(userId);
//
//
//        if (userinfoDTO == null) {
//            log.error("查询用户数据,无数据");
//            return new Result(true, StatusCode.NULL, "无数据");
//        }
//
//        log.info("查询用户成功,返回View");
//        return new Result(true, StatusCode.OK, "查询用户数据成功", userinfoDTO);
//
//    }

    /**
     * @hrows
     * @titlea 提交用户编辑
     * @description
     * @author liman
     */
    @PostMapping("/completeUpdateUserinfo")
    public Result completeUpdateUserinfo(@RequestBody String data) throws IOException {
        log.info("----------------------->>>completeUpdateUserinfo(@RequestBody String data) ");
        JSONObject jsonObject = JSON.parseObject(data);
        if (jsonObject == null) {
            throw new NullPointerException("空指针异常");
        }
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        String userId = jsonObject.getString("userId");
        String roleId = jsonObject.getString("roleId");
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(roleId)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }
        if (!StringUtils.isNumeric(userId) || !StringUtils.isNumeric(roleId)) {
            return new Result(false, StatusCode.ERROR, "参数格式有误");
        }

        userService.completeUpdateUserinfo(userId, roleId);


        log.info("编辑用户成功,返回View");
        return new Result(true, StatusCode.OK, "success");

    }

    @PostMapping("/getLeader")
    public Result getLeader() {
        log.info("----------------------->>>getLeader()");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }


        List<Name> nameList = userService.getRoleName("政府领导");

        if (nameList == null || nameList.size() == 0) {
            log.error("查询政府领导数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }


        log.info("查询政府领导成功,返回View");
        return new Result(true, StatusCode.OK, "查询政府领导成功", nameList);

    }

    @PostMapping("/getUnit")
    public Result getUnit() {
        log.info("----------------------->>>getUnit()");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        List<Name> nameList = userService.getRoleName("专项行动被考核单位");

        if (nameList == null) {
            log.error("查询专项行动被考核单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        if (nameList.size() == 0) {
            log.error("查询专项行动被考核单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }


        log.info("查询专项行动被考核单位数据,返回View");
        return new Result(true, StatusCode.OK, "查询专项行动被考核单位成功", nameList);

    }

    @PostMapping("/getCheckUnit")
    public Result getCheckUnit() {
        log.info("----------------------->>>getCheckUnit()");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        List<Name> nameList = userService.getRoleName("考核单位");

        if (nameList == null) {
            log.error("查询考核单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        if (nameList.size() == 0) {
            log.error("查询考核单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }


        log.info("查询考核单位数据,返回View");
        return new Result(true, StatusCode.OK, "查询考核单位数据成功", nameList);

    }

    @PostMapping("/getToCheckUnit")
    public Result getToCheckUnit() {
        log.info("----------------------->>>getToCheckUnit()");

        List<Name> nameList = userService.getRoleName("被考核单位");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        if (nameList == null) {
            log.error("查询被考核单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        if (nameList.size() == 0) {
            log.error("查询考核单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }


        log.info("查询考核单位数据,返回View");
        return new Result(true, StatusCode.OK, "查询考核单位数据成功", nameList);

    }

    @PostMapping("/getCauseUnit")
    public Result getCauseUnit() {
        log.info("----------------------->>>getToCheckUnit()");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        List<Name> nameList = userService.getRoleName("事业单位");

        if (nameList == null) {
            log.error("查询被事业单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        if (nameList.size() == 0) {
            log.error("查询事业单位数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }


        log.info("查询事业单位数据,返回View");
        return new Result(true, StatusCode.OK, "查询事业单位数据成功", nameList);

    }


    /**
     * @hrows
     * @titlea 查询所有地区
     * @description
     * @author liman
     */
    @PostMapping("/selectArea")
    public Result selectArea() {
        log.info("----------------------->>>selectArea()");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        List<Area> areaList = userService.selectArea();


        if (areaList == null && areaList.size() >= 1) {
            log.error("查询地区,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }

        log.info("查询用户成功,返回View");
        return new Result(true, StatusCode.OK, "查询地区数据成功", areaList);
    }

    /**
     * @hrows
     * @titlea 添加地区
     * @description
     * @author liman
     */
    @PostMapping("/insertArea")
    public Result insertArea(@RequestBody String data) {
        log.info("----------------------->>>insertArea() ");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        JSONObject jsonObject = JSON.parseObject(data);
        if (jsonObject == null) {
            throw new NullPointerException("空指针异常");
        }

        String areaName = jsonObject.getString("areaName");
        if (StringUtils.isBlank(areaName)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }
        userService.insertArea(areaName);


        log.info("添加成功,返回View");
        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/getRoleAll")
    public Result insertArea() {
        log.info("----------------------->>>getRoleAll() ");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        List<UserRole> userRoleList = userService.getRoleAll();


        log.info("添加成功,返回View");
        return new Result(true, StatusCode.OK, "查询成功", userRoleList);
    }


}
